package com.wpzf.ndhc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.License;
import com.ibm.icu.math.BigDecimal;
import com.wpzf.ndhc.domain.WpCjTbhcjgDTO;
import com.wpzf.ndhc.mapper.WpzfNdhcCommonMapper;
import com.wpzf.ndhc.mapper.WpzfNdhcTbBaseMapper;
import com.wpzf.ndhc.service.WpzfNdhcCommonService;
import com.wpzf.ndhc.utils.GTYUtil;
import com.wpzf.ndhc.utils.TableUtil;
import com.wpzf.zxhc.utils.NpoiHelper;
import com.wpzf.zxhc.utils.PdfUnits;
import com.wpzf.zxhc.utils.WordUnits;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WpzfNdhcCommonServiceImpl implements WpzfNdhcCommonService {

    @Autowired
    private WpzfNdhcCommonMapper wpzfNdhcCommonMapper;

    @Autowired
    private WpzfNdhcTbBaseMapper wpzfNdhcTbBaseMapper;

    @Value("${tempath}")
    private String tempath;

    @Override
    public Integer addHcjg(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.addHcjg(parm);
    }

    @Override
    public Integer addHcjg_hf_DtPwwj(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.addHcjg_hf_DtPwwj(parm);
    }

    @Override
    public Integer addHcjg_wf_wfpzwh(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.addHcjg_wf_wfpzwh(parm);
    }

    @Override
    public Integer addHcjg_wf_wftgzmwj(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.addHcjg_wf_wftgzmwj(parm);
    }

    @Override
    public Integer adddHcjg_qt_qtpzwh(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.adddHcjg_qt_qtpzwh(parm);
    }

    @Override
    public Integer addHcjg_qt_qtsftgxxydss(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.addHcjg_qt_qtsftgxxydss(parm);
    }

    @Override
    public Integer addHcjg_qt_qtsfzygd(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.addHcjg_qt_qtsfzygd(parm);
    }

    @Override
    public Integer deleteHcJg(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.deleteHcJg(parm);
    }

    @Override
    public Integer deleteHcjg_hf_dtPwwj(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.deleteHcjg_hf_dtPwwj(parm);
    }

    @Override
    public Integer deleteHcjg_wf_wfpzwh(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.deleteHcjg_wf_wfpzwh(parm);
    }

    @Override
    public Integer deleteHcjg_wf_wftgzmwj(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.deleteHcjg_wf_wftgzmwj(parm);
    }

    @Override
    public Integer deleteHcjg_qt_qtpzwh(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.deleteHcjg_qt_qtpzwh(parm);
    }

    @Override
    public Integer deleteHcjg_qt_qtsftgxxydss(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.deleteHcjg_qt_qtsftgxxydss(parm);
    }

    @Override
    public Integer deleteHcjg_qt_qtsfzygd(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.deleteHcjg_qt_qtsfzygd(parm);
    }

    @Override
    public Integer updateHcjg_hcjgsm(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.updateHcjg_hcjgsm(parm);
    }

    @Override
    public Map<String, Object> queryHcJgById(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.queryHcJgById(parm);
    }

    @Override
    public List<Map<String, Object>> queryHcJgByColumnName() {
        return wpzfNdhcCommonMapper.queryHcJgByColumnName();
    }

    @Override
    public List<Map<String, Object>> queryHftgzmwjByColumnName() {
        return wpzfNdhcCommonMapper.queryHftgzmwjByColumnName();
    }

    @Override
    public List<Map<String, Object>> queryWfpzwhByColumnName() {
        return wpzfNdhcCommonMapper.queryWfpzwhByColumnName();
    }

    @Override
    public List<Map<String, Object>> queryWftgzmwjByColumnName() {
        return wpzfNdhcCommonMapper.queryWftgzmwjByColumnName();
    }

    @Override
    public List<Map<String, Object>> queryQtpzwhByColumnName() {
        return wpzfNdhcCommonMapper.queryQtpzwhByColumnName();
    }

    @Override
    public List<Map<String, Object>> queryQtsftgxxydssByColumnName() {
        return wpzfNdhcCommonMapper.queryQtsftgxxydssByColumnName();
    }

    @Override
    public List<Map<String, Object>> queryQtsfzygdByColumnName() {
        return wpzfNdhcCommonMapper.queryQtsfzygdByColumnName();
    }

    @Override
    public Map<String, Object> getHcjgsmByDkbh(Map<String, Object> param) {
        Map<String, Object> tbInfo = wpzfNdhcCommonMapper.getTbInfo(param);
//        Map<String,Object> dkInfo = wpzfNdhcCommonServiceImpl.getDkInfo(param);
        String token = GTYUtil.getGTYToken();
//        String gtyRest = GTYUtil.getNDDxxxbsj2024(token, "00gty_wpzfnddk2024", param.get("xzqdm") + "", param.get("dkbh") + "");
        String gtyRest = "{\"data\":[{\"main\":{\"wpzfdk\":{\"tbbsm\":\"5abb617ee90841de9243f2dbf488d67d\",\"tbbh\":\"360733WPXZ00005\",\"dkbh\":\"360733202502040048\",\"sjtbmj\":2.53,\"jcrq\":\"20250204\",\"xzqdm\":\"360733\",\"tbfl\":\"\",\"xzmc\":\"\",\"csmc\":\"\",\"xxdz\":\"\",\"geometry\":\"POLYGON((115.729701926373 25.2851165121866,115.729761116962 25.2851147054877,115.729761271504 25.2851147366032,115.729777773608 25.2850732945253,115.72983880291 25.2848935575449,115.730106084189 25.2841063847249,115.730027284762 25.2840867162887,115.729915705578 25.2840616074065,115.729901503149 25.2840584118763,115.729897034441 25.2840574058465,115.729876939116 25.2840528824405,115.729835574131 25.2840895786642,115.730044936843 25.2841562660705,115.730050494084 25.2842279555255,115.729995991245 25.284316321931,115.729846818864 25.2844153368094,115.729719768413 25.2845088097859,115.729713366777 25.2845212471537,115.729630349082 25.2846825348194,115.729627610598 25.2846932581546,115.729620633806 25.2847326007303,115.729626839436 25.2847672813208,115.729642336465 25.2847924891076,115.729660596854 25.2848045864702,115.729672377962 25.2848082702256,115.72975932456 25.2849475979182,115.729764971193 25.28501069115,115.729701926373 25.2851165121866))\",\"gdmj\":2.4,\"qtnydmj\":0.13,\"jsydmj\":0.0,\"wlydmj\":0.0,\"hcjl\":\"\",\"sfjsyd\":\"Y\",\"sfnrhsqd\":\"Y\",\"tblx\":\"HFYD\",\"sjyt\":\"01\",\"sjyt2\":\"\",\"hfsjyt\":\"0601\",\"hfpdyjsm\":\"\",\"wflx1\":\"\",\"wflx2\":\"\",\"wfsjyt\":\"\",\"lzgdjf\":\"\",\"sywhzj\":\"\",\"sfdpf\":\"\",\"wfpdyjsm\":\"\",\"wf_xmlx\":\"\",\"wf_xmzt\":\"\",\"wf_xmmc\":\"\",\"wf_lxpzjg\":\"\",\"wf_lxpzwh\":\"\",\"wf_sfla\":\"\",\"qtydsjyt\":\"\",\"qtydsjyt2\":\"\",\"pwsj\":\"\",\"qtpdyjsm\":\"\",\"nrqduserlevel\":2}},\"other\":{\"hcfj\":[{\"bsm\":58330544,\"xzqdm\":\"360733\",\"tbbsm\":\"5abb617ee90841de9243f2dbf488d67d\",\"tbbh\":\"360733WPXZ00005\",\"fjmc\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/EDB9229963D74511979A3A7EC4D4EAA0F6DF822B4AA1A572F6AD96FDC042A82C_8532297376052868952.jpg\",\"lysb\":\"\",\"fjlx\":\"IMAGE\",\"psry\":\"范小三\",\"pssj\":\"2025-01-15 09:01:50\",\"longitude\":115.729678,\"latitude\":25.285091,\"psjd\":23,\"psgd\":\"229\",\"psfyj\":-23,\"psaltitude\":\"\",\"takeofflon\":\"\",\"takeofflat\":\"\",\"takeoffrelheight\":\"\",\"takeoffaltitude\":\"\",\"metarecord\":\"[{ \\\"accuracy\\\":3,\\\"x\\\":115.729678,\\\"y\\\":25.285091,\\\"yaw\\\":23,\\\"pitch\\\":-23,\\\"roll\\\":-1,\\\"distance\\\":\\\"\\\",\\\"height\\\":229}] \",\"arg\":\"EDB9229963D74511979A3A7EC4D4EAA0F6DF822B4AA1A572F6AD96FDC042A82C\",\"url\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/EDB9229963D74511979A3A7EC4D4EAA0F6DF822B4AA1A572F6AD96FDC042A82C_8532297376052868952.jpg\"},{\"bsm\":58330543,\"xzqdm\":\"360733\",\"tbbsm\":\"5abb617ee90841de9243f2dbf488d67d\",\"tbbh\":\"360733WPXZ00005\",\"fjmc\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/BFEDB99F451C03C4F05BE75AF14F3E320D34FB99AC9032FFD153CD4CC2A61038_8532297377752602252.jpg\",\"lysb\":\"\",\"fjlx\":\"IMAGE\",\"psry\":\"范小三\",\"pssj\":\"2025-01-15 09:01:06\",\"longitude\":115.72962,\"latitude\":25.2852535,\"psjd\":139,\"psgd\":\"226.18\",\"psfyj\":-12,\"psaltitude\":\"\",\"takeofflon\":\"\",\"takeofflat\":\"\",\"takeoffrelheight\":\"\",\"takeoffaltitude\":\"\",\"metarecord\":\"[{ \\\"accuracy\\\":3,\\\"x\\\":115.72962,\\\"y\\\":25.2852535,\\\"yaw\\\":139,\\\"pitch\\\":-12,\\\"roll\\\":-4,\\\"distance\\\":\\\"\\\",\\\"height\\\":226.18}] \",\"arg\":\"BFEDB99F451C03C4F05BE75AF14F3E320D34FB99AC9032FFD153CD4CC2A61038\",\"url\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/BFEDB99F451C03C4F05BE75AF14F3E320D34FB99AC9032FFD153CD4CC2A61038_8532297377752602252.jpg\"},{\"bsm\":58330542,\"xzqdm\":\"360733\",\"tbbsm\":\"5abb617ee90841de9243f2dbf488d67d\",\"tbbh\":\"360733WPXZ00005\",\"fjmc\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/40744840EF179FFABBB759D870CF14435700652DC8CEF6DAEF5E638A2FEE3111_8532297379111864052.jpg\",\"lysb\":\"\",\"fjlx\":\"IMAGE\",\"psry\":\"范小三\",\"pssj\":\"2025-01-15 09:01:46\",\"longitude\":115.729749,\"latitude\":25.285108,\"psjd\":335,\"psgd\":\"225.96\",\"psfyj\":-9,\"psaltitude\":\"\",\"takeofflon\":\"\",\"takeofflat\":\"\",\"takeoffrelheight\":\"\",\"takeoffaltitude\":\"\",\"metarecord\":\"[{ \\\"accuracy\\\":3,\\\"x\\\":115.729749,\\\"y\\\":25.285108,\\\"yaw\\\":335,\\\"pitch\\\":-9,\\\"roll\\\":-3,\\\"distance\\\":\\\"\\\",\\\"height\\\":225.96}] \",\"arg\":\"40744840EF179FFABBB759D870CF14435700652DC8CEF6DAEF5E638A2FEE3111\",\"url\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/40744840EF179FFABBB759D870CF14435700652DC8CEF6DAEF5E638A2FEE3111_8532297379111864052.jpg\"},{\"bsm\":58330541,\"xzqdm\":\"360733\",\"tbbsm\":\"5abb617ee90841de9243f2dbf488d67d\",\"tbbh\":\"360733WPXZ00005\",\"fjmc\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/2D181952D3CC1F26C7DFB3B904DCA91ECE52D725A5EC8E21AD48EDE127057D62_8532297378667584552.jpg\",\"lysb\":\"\",\"fjlx\":\"IMAGE\",\"psry\":\"范小三\",\"pssj\":\"2025-01-15 09:01:48\",\"longitude\":115.7296856,\"latitude\":25.2852781,\"psjd\":182,\"psgd\":\"225.65\",\"psfyj\":3,\"psaltitude\":\"\",\"takeofflon\":\"\",\"takeofflat\":\"\",\"takeoffrelheight\":\"\",\"takeoffaltitude\":\"\",\"metarecord\":\"[{ \\\"accuracy\\\":3,\\\"x\\\":115.7296856,\\\"y\\\":25.2852781,\\\"yaw\\\":182,\\\"pitch\\\":3,\\\"roll\\\":2,\\\"distance\\\":\\\"\\\",\\\"height\\\":225.65}] \",\"arg\":\"2D181952D3CC1F26C7DFB3B904DCA91ECE52D725A5EC8E21AD48EDE127057D62\",\"url\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/NDBG2024/406f6420b5fe4d9e838691770ffdf48e/2D181952D3CC1F26C7DFB3B904DCA91ECE52D725A5EC8E21AD48EDE127057D62_8532297378667584552.jpg\"}],\"pwinfo\":[{\"pwtbbsm\":\"f123cb98b97c5d6bac89431aa5b26122\",\"pzwhlx\":\"NYDZY\",\"pzwhlxtwo\":\"\",\"pwlb\":\"\",\"pzwh\":\"赣土批字（2022）257号\",\"pzsj\":\"2022-10-08 00:00:00\",\"pwly\":\"2\",\"pzmj\":230.93,\"pznydmj\":220.69,\"pzgdmj\":148.61,\"pzyjjbntmj\":0.0,\"reason\":\"\",\"pzjg\":\"江西省人民政府\"}],\"fjinfo\":[{\"tbbsm\":\"5abb617ee90841de9243f2dbf488d67d\",\"pwtbbsm\":\"f123cb98b97c5d6bac89431aa5b26122\",\"fjmc\":\"关于会昌县2022年度第3批次城市建设用地的批复.pdf\",\"fjurl\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/fjData/56cdb1b570274ee785278d546ba51b23/56cdb1b570274ee785278d546ba51b23/9f985982-bb99-855c-6709-c595e3b040fa_8532352841267112252.pdf\",\"fjlx\":\"PWPDYJ\"},{\"tbbsm\":\"5abb617ee90841de9243f2dbf488d67d\",\"pwtbbsm\":\"\",\"fjmc\":\"报批套合图_360733WPXZ00005.pdf\",\"fjurl\":\"https://gdhc-gj-012035.obs.cn-north-1.myhuaweicloud.com/G/360733/fjData/5abb617ee90841de9243f2dbf488d67d/5abb617ee90841de9243f2dbf488d67d/be284ff3-1ec3-1666-a1b3-b18551a726cd_8534187211922832152.pdf\",\"fjlx\":\"FJZL\"}]}}],\"total\":1,\"code\":200,\"status\":0,\"error\":null,\"message\":null}";

        JSONObject wpzfdk = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(gtyRest);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        if (dataArray != null && dataArray.size() > 0) {
            JSONObject data = dataArray.getJSONObject(0);
            JSONObject main = data.getJSONObject("main");
            wpzfdk = main.getJSONObject("wpzfdk");
        }

        //地块信息
        Map<String, Object> dkInfo = wpzfNdhcCommonMapper.getDkInfo(param);

        if (dkInfo != null && wpzfdk != null) {
            dkInfo.put("dkfw", wpzfdk.getString("geometry"));
            dkInfo.put("sfnrhsqd", wpzfdk.getString("sfnrhsqd"));
            dkInfo.put("sfnrhsqdmc", yesNoDictionary(wpzfdk.getString("sfnrhsqd")));
            dkInfo.put("hf_jtqx1", wpzfdk.getString("sjyt"));
            dkInfo.put("hf_jtqx1mc", hfjtqx1Dictionary(wpzfdk.getString("sjyt")));
            dkInfo.put("hf_jtqx2", wpzfdk.getString("sjyt2"));
            dkInfo.put("hf_jtqx2mc", hfjtqx2Dictionary(wpzfdk.getString("sjyt2")));
            dkInfo.put("hf_sjyt", wpzfdk.getString("hfsjyt"));
            dkInfo.put("hf_sjytmc", hfsjytDictionary(wpzfdk.getString("hfsjyt")));
            dkInfo.put("hf_pdyjsm", wpzfdk.getString("hfpdyjsm"));
            dkInfo.put("wf_wflx1", wpzfdk.getString("wflx1"));
            dkInfo.put("wf_wflx1mc", wflx1Dictionary(wpzfdk.getString("wflx1")));
            dkInfo.put("wf_wflx2", wpzfdk.getString("wflx2"));
            dkInfo.put("wf_wflx2mc", wflx2Dictionary(wpzfdk.getString("wflx2")));
            dkInfo.put("wf_sjyt", wpzfdk.getString("wfsjyt"));
            dkInfo.put("wf_sjytmc", wfsjytDictionary(wpzfdk.getString("wfsjyt")));
            dkInfo.put("sflzgdjf", wpzfdk.getString("lzgdjf"));
            dkInfo.put("sflzgdjfmc", yesNoDictionary(wpzfdk.getString("lzgdjf")));
            dkInfo.put("sfwhzj", wpzfdk.getString("sywhzj"));
            dkInfo.put("sfwhzjmc", yesNoDictionary(wpzfdk.getString("sywhzj")));
            dkInfo.put("sfdpf", wpzfdk.getString("sfdpf"));
            dkInfo.put("sfdpfmc", yesNoDictionary(wpzfdk.getString("sfdpf")));
            dkInfo.put("wf_pdyjsm", wpzfdk.getString("wfpdyjsm"));
            dkInfo.put("xmmc", wpzfdk.getString("wf_xmmc"));
            dkInfo.put("xmzt", wpzfdk.getString("wf_xmzt"));
            dkInfo.put("xmlx", wpzfdk.getString("wf_xmlx"));
            dkInfo.put("xmlxmc", xmlxDictionary(wpzfdk.getString("wf_xmlx")));
            dkInfo.put("lxpzjg", wpzfdk.getString("wf_lxpzjg"));
            dkInfo.put("lxpzwh", wpzfdk.getString("wf_lxpzwh"));
            dkInfo.put("wf_sfla", wpzfdk.getString("wf_sfla"));
            dkInfo.put("wf_sflamc", yesNoDictionary(wpzfdk.getString("wf_sfla")));
            dkInfo.put("qt_jtqx1", wpzfdk.getString("qtydsjyt"));
            dkInfo.put("qt_jtqx1mc", qtjtqx1Dictionary(wpzfdk.getString("qtydsjyt")));
            dkInfo.put("qt_jtqx2", wpzfdk.getString("qtydsjyt2"));
            dkInfo.put("qt_jtqx2mc", qtjtqx2Dictionary(wpzfdk.getString("qtydsjyt2")));
            dkInfo.put("pwsj", wpzfdk.getString("pwsj"));
            dkInfo.put("pwsjmc", pwsjDictionary(wpzfdk.getString("pwsj")));
            dkInfo.put("qt_pdyjsm", wpzfdk.getString("qtpdyjsm"));

            dkInfo.put("xzjd", wpzfdk.getString("xzmc"));
            dkInfo.put("csmc", wpzfdk.getString("csmc"));
            dkInfo.put("xxdz", wpzfdk.getString("xxdz"));
            dkInfo.put("nrqduserlevel", wpzfdk.getInteger("nrqduserlevel"));
        }


        Map<String, Object> tbhcjg = wpzfNdhcCommonMapper.getTbhcjg(param);
        Map<String, Object> tbhcjgZb = wpzfNdhcCommonMapper.getTbhcjgZb(param);

        Map<String, Object> mergedMap = new HashMap<>();
        mergedMap.putAll(tbInfo != null ? tbInfo : Collections.emptyMap());
        mergedMap.putAll(dkInfo != null ? dkInfo : Collections.emptyMap());
        mergedMap.putAll(tbhcjg != null ? tbhcjg : Collections.emptyMap());
        mergedMap.putAll(tbhcjgZb != null ? tbhcjgZb : Collections.emptyMap());

        return calculateHcjgsm(mergedMap);
    }

    private Map<String, Object> calculateHcjgsm(Map<String, Object> data) {
        Map<String, Object> result = new HashMap<>();
        String hcjgsm = resolveHcjgsmLogic(data);
        result.put("hcjgsm", hcjgsm);
        // 基础字段赋值
        result.put("dkbh", getString(data, "dkbh"));
        result.put("pdlx", getString(data, "pdlx"));
        result.put("xzqdm", getString(data, "xzqdm"));
        result.put("jcmj", getBigDecimal(data, "jcmj"));
        result.put("dlrdgdmj", getBigDecimal(data, "dlrdgdmj"));
        result.put("gdmj", getBigDecimal(data, "gdmj"));
        result.put("zphlxjc", coalesce(data, "hf_zphlxjc", "wf_zphlxjc", "qt_zphlxjc"));
        result.put("yxzpdl", coalesce(data, "hf_yxzpdl", "wf_yxzpdl", "qt_yxzpdl"));
        return result;
    }

    private String resolveHcjgsmLogic(Map<String, Object> data) {
        // 条件1：月清后修改（最高优先级）
        if (checkAnyBz(data, "月清后修改")) {
            return "月清后修改";
        }

        // 条件2：拆分后不占耕地
        if (hasDash(data) && isGdmjZero(data)) {
            return "拆分后不占耕地";
        }

        // 条件3：未填报完整信息
        if (checkAnyBz(data, "未填报完整信息")) {
            return "未填报完整信息";
        }

        String pdlx = getString(data, "pdlx");
        if ("已办理建设用地审批手续".equals(pdlx)) {
            return handleApprovedLand(data);
        } else if ("其他".equals(pdlx)) {
            return handleOtherType(data);
        }

        return "未发现问题";
    }

    private String handleApprovedLand(Map<String, Object> data) {
        String hfYxzpdl = getString(data, "hf_yxzpdl");
        String hfBz = getString(data, "hf_bz");
        String hfTbsmjsfyz = getString(data, "hf_tbsmjsfyz");
        String hfDjgptwthbfwjzcl = getString(data, "hf_djgptwthbfwjzcl");
        String hfTgzmwjsfkzwxzjsydpdyjdzj = getString(data, "hf_tgzmwjsfkzwxzjsydpdyjdzj");
        String hfSftgzlpwslsj = getString(data, "hf_sftgzlpwslsj");
        String hfZlpwlx = getString(data, "hf_zlpwlx");

        // 条件4-5：用地类型判断
        if (isApprovedLandType(hfYxzpdl)) {
            return "未办手续不占用耕地".equals(hfBz) ? "未办手续不占用耕地" : "未发现问题";
        }

        // 条件6：占用建设用地提供供地材料
        if ("占用建设用地提供供地材料".equals(hfBz)) {
            return "未发现问题";
        }

        // 条件7-14：详细证明材料判断
        if ("仅批文文号".equals(hfTbsmjsfyz)) return "提供证明材料不全（仅提供批准文号）";
        if ("填报文号与扫描件不一致".equals(hfTbsmjsfyz)) return "提供证明材料不全（填报文号与扫描件不一致）";
        if ("否".equals(hfDjgptwthbfwjzcl)) return "对监管平台未套合部分无举证材料";
        if ("否".equals(hfTgzmwjsfkzwxzjsydpdyjdzj)) return "提供证明文件不可作为新增建设用地判定依据";
        if (isValidApprovedLand(hfDjgptwthbfwjzcl, hfTgzmwjsfkzwxzjsydpdyjdzj, hfZlpwlx)) return "未发现问题";
        if ("提供矢量与扫描件一致，部分套合".equals(hfSftgzlpwslsj)) return "提供证明材料不全（自录批文位置矢量部分套合）";
        if ("提供矢量与批准文件不符".equals(hfSftgzlpwslsj)) return "提供证明材料不全（提供矢量与批准文件不符）";
        if ("提供矢量，批准文号为空".equals(hfSftgzlpwslsj)) return "提供证明材料不全（自录批文位置矢量批准文号为空）";
        if ("未提供".equals(hfSftgzlpwslsj)) return "提供证明材料不全（未提供自录批文位置矢量）";

        return "未发现问题";
    }

    private String handleOtherType(Map<String, Object> data) {
        String qtJtqx1mc = getString(data, "qt_jtqx1mc");
        String qtYxzpdl = getString(data, "qt_yxzpdl");
        String qtBz = getString(data, "qt_bz");
        String qtSffhsdwbhrdbz = getString(data, "qt_sffhsdwbhrdbz");
        BigDecimal gdmj = getBigDecimal(data, "gdmj");
        BigDecimal dlrdgdmj = getBigDecimal(data, "dlrdgdmj");

        // 条件15：其他图斑未填报实际用途
        if (isEmpty(qtJtqx1mc) && "其他图斑未填报实际用途".equals(qtBz)) {
            return "其他图斑未填报实际用途";
        }

        // 条件16：非粮化应办理建设用地审批手续而未办理(违法)违规用地
        if ("实地未变化".equals(qtJtqx1mc) &&
                "农村道路".equals(qtYxzpdl) &&
                "否".equals(qtSffhsdwbhrdbz) &&
                "农道占耕地未提供进出平衡方案".equals(qtBz) &&
                isGdmjExceed(gdmj, dlrdgdmj)) {
            return "非粮化应办理建设用地审批手续而未办理(违法)违规用地";
        }

        // 条件17-20：光伏用地处理
        if ("实地未变化".equals(qtJtqx1mc) &&
                "光伏".equals(qtYxzpdl) &&
                isGdmjExceed(gdmj, dlrdgdmj)) {
            return handleSolarLand(data);
        }

        // 条件21-32：临时用地处理
        if ("实地未变化".equals(qtJtqx1mc) && "临时用地".equals(qtYxzpdl)) {
            return handleTemporaryLand(data);
        }

        // 条件33-35：设施农用地处理
        if ("实地未变化".equals(qtJtqx1mc) &&
                isFacilityAgriculture(qtYxzpdl) &&
                "否".equals(qtSffhsdwbhrdbz) &&
                isGdmjExceed(gdmj, dlrdgdmj)) {
            return "非粮化应办理建设用地审批手续而未办理(违法)违规用地";
        }

        // 条件36-48：其他处理
        if ("现状不符合实地未变化认定标准".equals(qtBz)) return "现状不符合实地未变化认定标准";
        if ("设施农业用地".equals(qtJtqx1mc) && "批复内容与图斑情况不符".equals(qtBz)) return "批复内容与图斑情况不符";
        if (isMxjsyd(qtYxzpdl)) return "明显建设用地";
        if ("临时用地".equals(qtJtqx1mc) && "采矿用地".equals(qtYxzpdl) && isInvalidApproval(getString(data, "qt_pzwhysmjhlx"))) {
            return "未提供临时用地审批文件";
        }
        if (isLsydslwt(getString(data, "qt_slfwthqk"))) {
            return handleTemporaryVectorIssue(getString(data, "qt_slfwthqk"));
        }
        if ("不改变原用地性质的光伏用地".equals(qtJtqx1mc) &&
                "光伏".equals(qtYxzpdl) &&
                isGdmjExceed(gdmj, dlrdgdmj)) {
            return handleNonChangeSolarLand(data);
        }

        // 农村道路相关判断
        if ("农村道路".equals(qtJtqx1mc)) {
            if (isMxjsyd(qtYxzpdl)) {
                return "明显建设用地";
            }
            if ("否".equals(getString(data, "qt_sftgxjjcphcl")) && isGdmjExceed(gdmj, dlrdgdmj)) {
                return "非粮化应办理建设用地审批手续而未办理(违法)违规用地";
            }
        }

        return "未发现问题";
    }

    //------------------------ 辅助方法 (完整实现) ------------------------
    private boolean checkAnyBz(Map<String, Object> data, String value) {
        return value.equals(getString(data, "hf_bz")) ||
                value.equals(getString(data, "wf_bz")) ||
                value.equals(getString(data, "qt_bz"));
    }

    private boolean hasDash(Map<String, Object> data) {
        return getString(data, "dkbh").contains("-");
    }

    private boolean isGdmjZero(Map<String, Object> data) {
        return getBigDecimal(data, "gdmj").compareTo(BigDecimal.ZERO) == 0;
    }

    private boolean isApprovedLandType(String type) {
        return Arrays.asList("明显建筑物", "明显构筑物", "硬化地面", "铁路用地", "公路用地", "挖湖造景", "采矿用地", "拆除未尽").contains(type);
    }

    private boolean isValidApprovedLand(String djgptwth, String tgzmwj, String zlpwlx) {
        return ("是".equals(djgptwth) || isEmpty(djgptwth)) &&
                "是".equals(tgzmwj) &&
                zlpwlx.contains("先行用地");
    }

    private boolean isGdmjExceed(BigDecimal gdmj, BigDecimal dlrdgdmj) {
        return gdmj.compareTo(BigDecimal.ONE) >= 0 || dlrdgdmj.compareTo(BigDecimal.ONE) >= 0;
    }

    private String handleSolarLand(Map<String, Object> data) {
        String qtBawjsfhl = getString(data, "qt_bawjsfhl");
        String qtTgbawjsj = getString(data, "qt_tgbawjsj");

        if ("未提供".equals(qtBawjsfhl)) return "光伏用地占用耕地，未提供备案文件";
        if ("不合理".equals(qtBawjsfhl)) return "光伏用地占用耕地，提供备案文件不合理";
        if (isValidSolarApprovalDate(qtTgbawjsj)) return "光伏用地占用耕地";
        return "未发现问题";
    }

    private boolean isValidSolarApprovalDate(String dateStr) {
        try {
            Date approvalDate = new SimpleDateFormat("yyyyMMdd").parse(dateStr);
            Date cutoffDate = new SimpleDateFormat("yyyyMMdd").parse("20221130");
            return approvalDate.after(cutoffDate);
        } catch (Exception e) {
            return false;
        }
    }

    private String handleTemporaryLand(Map<String, Object> data) {
        String qtBz = getString(data, "qt_bz");
        String qtSftglsydpf = getString(data, "qt_sftglsydpf");
        String qtPzwhysmjhlx = getString(data, "qt_pzwhysmjhlx");
        String qtSlfwthqk = getString(data, "qt_slfwthqk");
        String qtPzwh = getString(data, "qt_pzwh");
        String qtPzxmmc = getString(data, "qt_pzxmmc");
        String qtPzsj = getString(data, "qt_pzsj");

        // 新增：检查字段是否非空（问题二修复）
        boolean isFieldsValid = !isEmpty(qtPzwh) && !isEmpty(qtPzxmmc) && !isEmpty(qtPzsj);
        if (!isFieldsValid) {
            return "未提供临时用地审批文件（关键字段缺失）";
        }

        if ("批复内容与图斑情况不符".equals(qtBz)) return "批复内容与图斑情况不符";
        if ("否".equals(qtSftglsydpf)) return "现状不符合实地未变化认定标准";
        if (isInvalidApproval(qtPzwhysmjhlx)) return "未提供临时用地审批文件";
        if (isLsydslwt(qtSlfwthqk)) return handleTemporaryVectorIssue(qtSlfwthqk);
        return "未发现问题";
    }

    private boolean isInvalidApproval(String status) {
        return Arrays.asList("不合理", "未提供扫描件", "批准文号与扫描件不一致").contains(status);
    }

    private boolean isLsydslwt(String status) {
        return Arrays.asList("提供矢量与扫描件一致，部分套合", "提供矢量与批准文件不符", "未提供").contains(status);
    }

    private String handleTemporaryVectorIssue(String status) {
        switch (status) {
            case "提供矢量与扫描件一致，部分套合":
                return "未提供临时用地审批文件（临时用地位置矢量部分套合）";
            case "提供矢量与批准文件不符":
                return "未提供临时用地审批文件（临时用地位置矢量与批准文件不符）";
            case "未提供":
                return "未提供临时用地审批文件（未提供临时用地位置矢量）";
            default:
                return "未发现问题";
        }
    }

    private boolean isFacilityAgriculture(String type) {
        return Arrays.asList("设施农用地", "在建设施农用地").contains(type);
    }

    private boolean isMxjsyd(String type) {
        return Arrays.asList("明显建筑物", "明显构筑物", "硬化地面", "铁路用地", "公路用地", "挖湖造景", "采矿用地", "拆除未尽").contains(type);
    }

    private String handleNonChangeSolarLand(Map<String, Object> data) {
        String qtBawjsfhl = getString(data, "qt_bawjsfhl");
        String qtTgbawjsj = getString(data, "qt_tgbawjsj");

        if ("未提供".equals(qtBawjsfhl)) return "光伏用地占用耕地，未提供备案文件";
        if ("不合理".equals(qtBawjsfhl)) return "光伏用地占用耕地，提供备案文件不合理";
        if (isValidSolarApprovalDate(qtTgbawjsj)) return "光伏用地占用耕地";
        return "未发现问题";
    }

    //------------------------ 基础工具方法 ------------------------
    private String coalesce(Map<String, Object> data, String... fields) {
        for (String field : fields) {
            String value = getString(data, field);
            if (!isEmpty(value)) return value;
        }
        return "";
    }

    private boolean isEmpty(String value) {
        return value == null || value.trim().isEmpty();
    }

    private String getString(Map<String, Object> data, String key) {
        Object value = data.get(key);
        return (value != null) ? value.toString().trim() : "";
    }

    private BigDecimal getBigDecimal(Map<String, Object> data, String key) {
        try {
            Object value = data.get(key);
            if (value instanceof Number) {
                return BigDecimal.valueOf(((Number) value).doubleValue());
            }
            return new BigDecimal(value.toString().trim());
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }






    public String yesNoDictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryYesnoByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String hfjtqx1Dictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryHfjtqx1ByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String hfjtqx2Dictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryHfjtqx2ByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String hfsjytDictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryHfsjytByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String wflx1Dictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryWflx1ByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String wflx2Dictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryWflx2ByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String wfsjytDictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryWfsjytByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String xmlxDictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryXmlxByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String qtjtqx1Dictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryQtjtqx1ByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String qtjtqx2Dictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryQtjtqx2ByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    public String pwsjDictionary(String param) {
        Map<String, Object> map = wpzfNdhcTbBaseMapper.queryPwsjByKey(param);
        return map != null ? map.get("value") + "" : null;
    }

    @Override
    public List<WpCjTbhcjgDTO> getTbhcjglist(Map<String, Object> parm) {
        parm = TableUtil.TableName(parm);
        return wpzfNdhcCommonMapper.getTbhcjglist(parm);
    }

    @Override
    public List<Map<String, Object>> get_user_pchlist(Map<String, Object> parm) {
        parm = TableUtil.TableName(parm);
        return wpzfNdhcCommonMapper.get_user_pchlist(parm);
    }

    @Override
    public List<Map<String, Object>> get_unit_userlist(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.get_unit_userlist(parm);
    }

    @Override
    public List<Map<String, Object>> getTbbhList(Map<String, Object> parm) {
        return wpzfNdhcCommonMapper.getTbbhList(parm);
    }

    @Override
    public Map<String, Object> query_user_realname(Map<String, Object> parm) {
        parm = TableUtil.TableName(parm);
        return wpzfNdhcCommonMapper.query_user_realname(parm);
    }

    @Override
    public int updateHcjg_sftj(Map<String, Object> parm) {
        parm = TableUtil.TableName(parm);
        return wpzfNdhcCommonMapper.updateHcjg_sftj(parm);
    }

    @Override
    public List<Map<String, Object>> getJlPch(Map<String, Object> parm) {
        // parm = TableUtil.TableName(parm);
        return wpzfNdhcCommonMapper.getJlPch(parm);
    }

    @Override
    public List<Map<String, Object>> getNdhcYear(Map<String, Object> parm) {
//        parm = TableUtil.TableName(parm);
        return wpzfNdhcCommonMapper.getNdhcYear(parm);
    }

    @Override
    @Transactional
    public Integer savePdfInfo(Map<String, Object> param) {
        wpzfNdhcCommonMapper.deletePdfInfo(param);
        return wpzfNdhcCommonMapper.savePdfInfo(param);
    }

    @Override
    public Map<String, Object> getPdfInfo(Map<String, Object> param) {
        return wpzfNdhcCommonMapper.getPdfInfo(param);
    }

    @Override
    public Map<String, Object> getHcjgsmlx(Map<String, Object> param) {
        return wpzfNdhcCommonMapper.getHcjgsmlx(param);
    }

    @Override
    public String getPDF(Map<String, Object> param, HttpServletResponse response) {
        String rest = "";
        try {
            if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
                return "";
            }
            String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String wordFilePath = tempath + "/WORD_" + yyyyMMddHHmmss + ".docx";
            String pdfFilePath = tempath + "/PDF_" + yyyyMMddHHmmss + ".pdf";

            String dkbh = param.get("dkbh") + "";
            String pdlx = param.get("pdlx") + "";

            String zp1 = param.get("zp1") + "";
            String zp1Url = "";
            if (!"".equals(zp1)) {
                zp1Url = downloadFile(param.get("zp1") + "", tempath, "zp1");
            }
            String zp2 = param.get("zp2") + "";
            String zp2Url = "";
            if (!"".equals(zp2)) {
                zp2Url = downloadFile(param.get("zp2") + "", tempath, "zp2");
            }
            String zp3 = param.get("zp3") + "";
            String zp3Url = "";
            if (!"".equals(zp3)) {
                zp3Url = downloadFile(param.get("zp3") + "", tempath, "zp3");
            }
            String zp4 = param.get("zp4") + "";
            String zp4Url = "";
            if (!"".equals(zp4)) {
                zp4Url = downloadFile(param.get("zp4") + "", tempath, "zp4");
            }

            if ("其他".equals(pdlx)) {
                String qt_jtqx1mc = param.get("qt_jtqx1mc") + "";
                String nzy = param.get("nzy") + "";
                String jcmj = param.get("jcmj") + "";
                String dkmj = param.get("dkmj") + "";
                String gdmj = param.get("gdmj") + "";
                String qtnydmj = param.get("qtnydmj") + "";
                String jsydmj = param.get("jsydmj") + "";
                String wlydmj = param.get("wlydmj") + "";
                String lsydpzwh = param.get("lsydpzwh") + "";
                String ssnydpzwh = param.get("ssnydpzwh") + "";
                String cchcjg = param.get("cchcjg") + "";
                String cchcjgsm = param.get("cchcjgsm") + "";
                String fhhcjg = param.get("fhhcjg") + "";
                String fhhcjgsm = param.get("fhhcjgsm") + "";
                String bz = param.get("bz") + "";

                FileInputStream fis = new FileInputStream(tempath + "\\导出PDF模板\\卫片其他模板2024.docx");
                XWPFDocument document = new XWPFDocument(fis);
                WordUnits.replaceText(document, "{dkbh}", dkbh);

                if (!"".equals(zp1)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp1}", zp1Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp1}", "");
                }
                if (!"".equals(zp2)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp2}", zp2Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp2}", "");
                }
                if (!"".equals(zp3)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp3}", zp3Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp3}", "");
                }
                if (!"".equals(zp4)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp4}", zp4Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp4}", "");
                }

                WordUnits.replaceTablePlaceholders(document, "{qt_jtqx1mc}", qt_jtqx1mc);
                WordUnits.replaceTablePlaceholders(document, "{nzy}", nzy);
                WordUnits.replaceTablePlaceholders(document, "{jcmj}", jcmj);
                WordUnits.replaceTablePlaceholders(document, "{dkmj}", dkmj);
                WordUnits.replaceTablePlaceholders(document, "{gdmj}", gdmj);
                WordUnits.replaceTablePlaceholders(document, "{qtnydmj}", qtnydmj);
                WordUnits.replaceTablePlaceholders(document, "{jsydmj}", jsydmj);
                WordUnits.replaceTablePlaceholders(document, "{wlydmj}", wlydmj);
                WordUnits.replaceTablePlaceholders(document, "{lsydpzwh}", lsydpzwh);
                WordUnits.replaceTablePlaceholders(document, "{ssnydpzwh}", ssnydpzwh);
                WordUnits.replaceTablePlaceholders(document, "{cchcjg}", cchcjg);
                WordUnits.replaceTablePlaceholders(document, "{cchcjgsm}", cchcjgsm);
                WordUnits.replaceTablePlaceholders(document, "{fhhcjg}", fhhcjg);
                WordUnits.replaceTablePlaceholders(document, "{fhhcjgsm}", fhhcjgsm);
                WordUnits.replaceTablePlaceholders(document, "{bz}", bz);

                FileOutputStream fos = new FileOutputStream(wordFilePath);
                document.write(fos);
                fos.close();
                fis.close();
                document.close();

                // PDF文件流
//            ByteArrayOutputStream byteArrayOutputStream = WordUnits.wordToPdfStream(wordFilePath);
//            return byteArrayOutputStream.toString();
            } else if ("应办理建设用地审批手续而未办理".equals(pdlx)) {
                String nzy = param.get("nzy") + "";
                String jcmj = param.get("jcmj") + "";
                String dkmj = param.get("dkmj") + "";
                String gdmj = param.get("gdmj") + "";
                String qtnydmj = param.get("qtnydmj") + "";
                String jsydmj = param.get("jsydmj") + "";
                String wlydmj = param.get("wlydmj") + "";
                String wf_wflx1mc = param.get("wf_wflx1mc") + "";
                String wf_zglsdwqk = param.get("wf_zglsdwqk") + "";
                String nzypzwh = param.get("nzypzwh") + "";
                String xxydpzwh = param.get("xxydpzwh") + "";
                String ssnydpzwh = param.get("ssnydpzwh") + "";
                String cchcjg = param.get("cchcjg") + "";
                String cchcjgsm = param.get("cchcjgsm") + "";
                String fhhcjg = param.get("fhhcjg") + "";
                String fhhcjgsm = param.get("fhhcjgsm") + "";
                String bz = param.get("bz") + "";

                FileInputStream fis = new FileInputStream(tempath + "\\导出PDF模板\\卫片应办理建设用地审批手续而未办理模板2024.docx");
                XWPFDocument document = new XWPFDocument(fis);
                WordUnits.replaceText(document, "{dkbh}", dkbh);

                if (!"".equals(zp1)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp1}", zp1Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp1}", "");
                }
                if (!"".equals(zp2)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp2}", zp2Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp2}", "");
                }
                if (!"".equals(zp3)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp3}", zp3Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp3}", "");
                }
                if (!"".equals(zp4)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp4}", zp4Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp4}", "");
                }

                WordUnits.replaceTablePlaceholders(document, "{nzy}", nzy);
                WordUnits.replaceTablePlaceholders(document, "{jcmj}", jcmj);
                WordUnits.replaceTablePlaceholders(document, "{dkmj}", dkmj);
                WordUnits.replaceTablePlaceholders(document, "{gdmj}", gdmj);
                WordUnits.replaceTablePlaceholders(document, "{qtnydmj}", qtnydmj);
                WordUnits.replaceTablePlaceholders(document, "{jsydmj}", jsydmj);
                WordUnits.replaceTablePlaceholders(document, "{wlydmj}", wlydmj);
                WordUnits.replaceTablePlaceholders(document, "{wf_wflx1mc}", wf_wflx1mc);
                WordUnits.replaceTablePlaceholders(document, "{wf_zglsdwqk}", wf_zglsdwqk);
                WordUnits.replaceTablePlaceholders(document, "{nzypzwh}", nzypzwh);
                WordUnits.replaceTablePlaceholders(document, "{xxydpzwh}", xxydpzwh);
                WordUnits.replaceTablePlaceholders(document, "{ssnydpzwh}", ssnydpzwh);
                WordUnits.replaceTablePlaceholders(document, "{cchcjg}", cchcjg);
                WordUnits.replaceTablePlaceholders(document, "{cchcjgsm}", cchcjgsm);
                WordUnits.replaceTablePlaceholders(document, "{fhhcjg}", fhhcjg);
                WordUnits.replaceTablePlaceholders(document, "{fhhcjgsm}", fhhcjgsm);
                WordUnits.replaceTablePlaceholders(document, "{bz}", bz);

                FileOutputStream fos = new FileOutputStream(wordFilePath);
                document.write(fos);
                fos.close();
                fis.close();
                document.close();

                // PDF文件流
//            ByteArrayOutputStream byteArrayOutputStream = WordUnits.wordToPdfStream(wordFilePath);
//            return byteArrayOutputStream.toString();
            } else if ("已办理建设用地审批手续".equals(pdlx)) {
                String nzy = param.get("nzy") + "";
                String pzwh = param.get("pzwh") + "";
                String jcmj = param.get("jcmj") + "";
                String dkmj = param.get("dkmj") + "";
                String gdmj = param.get("gdmj") + "";
                String qtnydmj = param.get("qtnydmj") + "";
                String jsydmj = param.get("jsydmj") + "";
                String wlydmj = param.get("wlydmj") + "";
                String cchcjg = param.get("cchcjg") + "";
                String cchcjgsm = param.get("cchcjgsm") + "";
                String fhhcjg = param.get("fhhcjg") + "";
                String fhhcjgsm = param.get("fhhcjgsm") + "";
                String bz = param.get("bz") + "";

                FileInputStream fis = new FileInputStream(tempath + "\\导出PDF模板\\卫片已办理建设用地审批手续模板2024.docx");
                XWPFDocument document = new XWPFDocument(fis);
                WordUnits.replaceText(document, "{dkbh}", dkbh);

                if (!"".equals(zp1)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp1}", zp1Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp1}", "");
                }
                if (!"".equals(zp2)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp2}", zp2Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp2}", "");
                }
                if (!"".equals(zp3)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp3}", zp3Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp3}", "");
                }
                if (!"".equals(zp4)) {
                    WordUnits.replaceTextWithImageInTables(document, "{zp4}", zp4Url, 200, 200);
                } else {
                    WordUnits.replaceTablePlaceholders(document, "{zp4}", "");
                }

                WordUnits.replaceTablePlaceholders(document, "{nzy}", nzy);
                WordUnits.replaceTablePlaceholders(document, "{pzwh}", pzwh);
                WordUnits.replaceTablePlaceholders(document, "{jcmj}", jcmj);
                WordUnits.replaceTablePlaceholders(document, "{dkmj}", dkmj);
                WordUnits.replaceTablePlaceholders(document, "{gdmj}", gdmj);
                WordUnits.replaceTablePlaceholders(document, "{qtnydmj}", qtnydmj);
                WordUnits.replaceTablePlaceholders(document, "{jsydmj}", jsydmj);
                WordUnits.replaceTablePlaceholders(document, "{wlydmj}", wlydmj);
                WordUnits.replaceTablePlaceholders(document, "{cchcjg}", cchcjg);
                WordUnits.replaceTablePlaceholders(document, "{cchcjgsm}", cchcjgsm);
                WordUnits.replaceTablePlaceholders(document, "{fhhcjg}", fhhcjg);
                WordUnits.replaceTablePlaceholders(document, "{fhhcjgsm}", fhhcjgsm);
                WordUnits.replaceTablePlaceholders(document, "{bz}", bz);

                FileOutputStream fos = new FileOutputStream(wordFilePath);
                document.write(fos);
                fos.close();
                fis.close();
                document.close();

                // PDF文件流
//            ByteArrayOutputStream byteArrayOutputStream = WordUnits.wordToPdfStream(wordFilePath);
//            return byteArrayOutputStream.toString();
            }

            NpoiHelper.doc2pdf(wordFilePath, pdfFilePath);
            rest = "PDF_" + yyyyMMddHHmmss + ".pdf";

            List<Map<String, Object>> attachments = (List<Map<String, Object>>) param.get("attachments");
            if (attachments != null && attachments.size() > 0) {
                PDDocument doc = new PDDocument();
                PdfUnits.appendPDF(doc, pdfFilePath);
                for (Map<String, Object> attachment : attachments) {
                    String file = downloadFile(attachment.get("fjurl") + "", tempath);
                    String extension = getFileExtension(file);
                    switch (extension) {
                        case ".jpg":
                        case ".png":
                            PdfUnits.addImageToPDF(doc, file);
                            break;
                        case ".docx":
                        case ".doc":
                            PdfUnits.addDocxToPDF(doc, file, tempath + "/wordToPDF_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".pdf");
                            break;
                        case ".pdf":
                            PdfUnits.appendPDF(doc, file);
                            break;
                        default:
                            System.out.println("Unsupported file format: " + file);
                    }
                }
                doc.save(pdfFilePath);
            }

            File file = new File(pdfFilePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            fileInputStream.read(bytes);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"file.pdf\"");
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = byteArrayInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            byteArrayInputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception ex) {
            rest = "error : " + ex.toString();
        }
        return rest;
    }

    public static boolean getLicense() {
        boolean result = false;
        InputStream is = null;
        try {
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                    "<License>\n" +
                    "    <Data>\n" +
                    "        <Products>\n" +
                    "            <Product>Aspose.Total for Java</Product>\n" +
                    "            <Product>Aspose.Words for Java</Product>\n" +
                    "        </Products>\n" +
                    "        <EditionType>Enterprise</EditionType>\n" +
                    "        <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                    "        <LicenseExpiry>20991231</LicenseExpiry>\n" +
                    "        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                    "    </Data>\n" +
                    "    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                    "</License>\n";
            is = new ByteArrayInputStream(xml.getBytes());
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    // 从给定的URL下载文件，并保存到指定目录
    private String downloadFile(String fileURL, String saveDirectory, String type) throws IOException {
        // 确保文件夹存在
        File directory = new File(saveDirectory);
        if (!directory.exists()) {
            if (directory.mkdirs()) {
                System.out.println("目录不存在，已创建: " + saveDirectory);
            } else {
                throw new IOException("无法创建目录: " + saveDirectory);
            }
        }

        // 生成基于当前时间的文件名
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSSXXX").format(new Date());
        String fileName = "/PDF_file_" + type + "_" + timestamp + getFileExtension(fileURL);
        String saveFilePath = saveDirectory + File.separator + fileName;

        // 下载文件
        URL url = new URL(fileURL);
        try (InputStream inputStream = new BufferedInputStream(url.openStream());
             FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath)) {

            byte[] dataBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
        }
        return saveFilePath;
    }

    private String downloadFile(String fileURL, String saveDirectory) throws IOException {
        // 确保文件夹存在
        File directory = new File(saveDirectory);
        if (!directory.exists()) {
            if (directory.mkdirs()) {
                System.out.println("目录不存在，已创建: " + saveDirectory);
            } else {
                throw new IOException("无法创建目录: " + saveDirectory);
            }
        }

        // 生成基于当前时间的文件名
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSSXXX").format(new Date());
        String fileName = "/PDF_file_" + timestamp + getFileExtension(fileURL);
        String saveFilePath = saveDirectory + fileName;

        // 下载文件
        URL url = new URL(fileURL);
        try (InputStream inputStream = new BufferedInputStream(url.openStream());
             FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath)) {

            byte[] dataBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
        }
        return saveFilePath;
    }

    // 获取文件的扩展名
    private static String getFileExtension(String fileURL) {
        String fileName = fileURL.substring(fileURL.lastIndexOf('/') + 1);
        if (fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf('.'));
        } else {
            return "";  // 如果没有扩展名，返回空字符串
        }
    }

    
    
    
    

    @Override
    public Map<String, Object> getTbInfo(Map<String, Object> param) {
        return wpzfNdhcCommonMapper.getTbInfo(param);
    }

    @Override
    public Map<String, Object> getDkInfo(Map<String, Object> param) {
        return wpzfNdhcCommonMapper.getDkInfo(param);
    }

    @Override
    public Map<String, Object> getTbhcjg(Map<String, Object> param) {
        return wpzfNdhcCommonMapper.getTbhcjg(param);
    }
}
